package com.xs;

import lombok.Data;
import lombok.ToString;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @program: paxos-java-demo
 * @description 提案
 * @author: wzx
 * @create: 2021-07-08 17:38
 **/

@Data
@ToString
public class Proposal implements Comparable<Proposal> {

    private static final String[] PROPOSALS = {"ProjectA", "ProjectB", "ProjectC"};
    private static final Random RANDOM=new Random();

    private long no; //提案编号
    private String content; //提案内容

    public Proposal(long no,String content){
        this.no=no;
        this.content=content;
    }

    public Proposal()
    {
        this(-1,null);
    }

    /**
     * 如果maxVote 不存在，没有限制,下一次表决可以使用任提案
     * 否则下一次表决沿用maxVote的提案
     * @param currentNo
     * @param proposas
     * @return
     */
    public static Proposal nextProposal(long currentNo, List<Proposal> proposas)
    {
        long no=currentNo+1;
        if(proposas.isEmpty())
            return new Proposal(no,PROPOSALS[RANDOM.nextInt(PROPOSALS.length)]);
        Proposal maxVote=proposas.get(proposas.size()-1); //取最大提案
        Collections.sort(proposas);
        long maxNo=maxVote.getNo(); //最大提案编号
        if(maxNo>=currentNo)
            throw new IllegalStateException("illegal state maxVoteNumber");
        String context=maxVote.getContent();  //获取最大提案的内容
        if(context==null)
            return new Proposal(no,PROPOSALS[RANDOM.nextInt(PROPOSALS.length)]);
        else{
            return new Proposal(no,context);
        }
    }


    public int compareTo(Proposal o) {
        return Long.compare(no,o.no);
    }
}
